from django.db.models.signals import m2m_changed, post_delete, post_save
from django.dispatch import receiver

from .models import KnowledgeNode
from .neo4j_service import delete_knowledge_node, sync_knowledge_node, sync_prerequisites


@receiver(post_save, sender=KnowledgeNode)
def sync_node_to_neo4j(sender, instance, **kwargs):
    sync_knowledge_node(instance)
    # Ensure properties and edges stay in sync after each save
    sync_prerequisites(instance, instance.prerequisites.values_list("id", flat=True))


@receiver(post_delete, sender=KnowledgeNode)
def remove_node_from_neo4j(sender, instance, **kwargs):
    delete_knowledge_node(instance.id)


@receiver(m2m_changed, sender=KnowledgeNode.prerequisites.through)
def handle_prerequisite_changes(sender, instance, action, **kwargs):
    if action in {"post_add", "post_remove", "post_clear"}:
        sync_prerequisites(instance, instance.prerequisites.values_list("id", flat=True))
